package com.exam.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.exam.common.vo.page.SystemContext;

public class SystemContextFilter implements Filter {

	private Integer offset;
	private Integer pageSize;
	
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		try {
			offset = Integer.parseInt(request.getParameter("pager.offset"));
		} catch (NumberFormatException e) {
			offset = 0;
		}
		try {
			SystemContext.setOffset(offset);
			SystemContext.setPageSize(pageSize);
			chain.doFilter(request, response);
		} catch (Exception e) {
			SystemContext.removeOffset();
			SystemContext.removePageSize();
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		try {
			pageSize = Integer.parseInt(filterConfig.getInitParameter("pageSize"));
		} catch (NumberFormatException e) {
			pageSize = 6;
		}
	}

}
